package com.happyscan138.makefun.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.happyscan138.makefun.R;
import com.happyscan138.makefun.Urls.Urls;
import com.happyscan138.makefun.VideoDetail;
import com.happyscan138.makefun.VideoviewPlay;
import com.happyscan138.makefun.View.RoundImageView;
import com.happyscan138.makefun.base.LoadListView;
import com.happyscan138.makefun.base.VideoInfo;
import com.happyscan138.makefun.base.VideoPlayView;
import com.happyscan138.makefun.base.WaitNetDataPop;
import com.happyscan138.makefun.more_myself;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static android.content.Context.MODE_PRIVATE;
import static com.happyscan138.makefun.base.http.client;
import static com.happyscan138.makefun.base.http.params;
import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2016/12/15.
 */

public class Persionalvideo extends Fragment implements VideoPlayView.MediaPlayerImpl, AbsListView.OnScrollListener{
    private SharedPreferences preferences;
    private String accessy_ley;
    private View footer;// 底部布局
    private int totalItemCount;// 总数量
    private int lastVisibieItem;// 最后一个可见的item;
    private boolean isLoading;// 判断变量
    private LoadListView videoList;
    private MyAdapter adapter;
    private VideoPlayView playView;
    private View currentItemView;
    private int currentPosition = -1;
    private List<VideoInfo> ListData;
    private boolean isPlaying;
    private int firstVisiblePosition;
    private VideoInfo data;
    private int  PROBLEM_ID_INDEX ;
    private SwipeRefreshLayout mSwipeLayout;
    private Handler handler;
    private WaitNetDataPop waitNetDataPop;
    private ArrayList<Integer> ID;
    //Tab用来标记集合第一个元素，是否发生变化，用来做下拉刷新
    private int Tab;
    private int IfRefresh;
    private String userID;

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.battle_new,null);
        userID=getArguments().getString("user_id");
        preferences = getActivity().getSharedPreferences("UserInfo", MODE_PRIVATE);
        accessy_ley=preferences.getString("UserId","");
        ID=new ArrayList<Integer>();
        client =new AsyncHttpClient();
        params =new RequestParams();
        initView(view);
        waitNetDataPop=new WaitNetDataPop(getActivity());
        waitNetDataPop.displayPop();
        initData();
        return view;
    }

    private void initView(View view) {
        videoList = (LoadListView) view.findViewById(R.id.battle_new_listview);
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        footer = inflater.inflate(R.layout.footermore, null);
        // 设置隐藏底部布局
        footer.findViewById(R.id.footer_layout).setVisibility(View.GONE);
        videoList.addFooterView(footer);
        mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.video_new_id_swipe_ly);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                params.put("access_key",accessy_ley);
                params.put("page_count",10);
                params.put("problem_id_index",0);
                params.put("user_id",userID);
                RequestHandle handle = client.post(Urls.VideoPer, params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String jsonStr = response.toString();
                        try {
                            JSONObject jsonObject = new JSONObject(jsonStr);
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            JSONObject obj=jsonArray.getJSONObject(0);
                            IfRefresh=obj.getInt("problem_id");
                            log.e("IfRefresh",IfRefresh+"");
                            log.e("IfRefresh",Tab+"");
                            if (IfRefresh == Tab) {
                                Toast.makeText(getActivity(), "已是最新数据", Toast.LENGTH_SHORT).show();
                            }    else {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject objectData = jsonArray.getJSONObject(i);
                                    PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                                    ID.add(PROBLEM_ID_INDEX);
                                    log.e("IfRefresh",ID.toString());
                                    data=new VideoInfo();
                                    data.userID = objectData.getString("user_id");
                                    log.e("user_id", data.userID + "");
                                    data.userID=objectData.getString("user_id");
                                    data.ima_path = Urls.base + objectData.getString("img_path");
                                    log.e("icon", data.ima_path.toString());
                                    data.name = objectData.getString("nick_name");
                                    data.time = objectData.getString("create_date");
                                    data.content = objectData.getString("content");
                                    data.url = Urls.base + objectData.getString("resource");
                                    data.Thumb=Urls.base+objectData.get("thumb");
                                    data.read_count = objectData.getInt("read_count");
                                    data.replay_count = objectData.getInt("replay_count");
                                    data.asmire_count = objectData.getInt("admire_count");
                                    data.problem_id = objectData.getString("problem_id");
                                    ListData.add(data);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
                mSwipeLayout.setRefreshing(false);
            }
        });
    }

    private void initData() {
        adapter = new MyAdapter(getActivity());
        videoList.setOnScrollListener(this);
        ListData = new ArrayList<>();
        params.put("access_key",accessy_ley);
        params.put("page_count",10);
        params.put("problem_id_index",0);
        params.put("user_id",userID);
        log.e("params",params.toString());
        RequestHandle handle= client.post(Urls.VideoPer, params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                waitNetDataPop.dismiss();
                String jsonStr=response.toString();
                log.e("jsonstr",jsonStr);
                try {
                    JSONObject jsonObject=new JSONObject(jsonStr);
                    JSONArray jsonArray=jsonObject.getJSONArray("data");
                    for (int i=0;i<jsonArray.length();i++){
                        JSONObject objectData=jsonArray.getJSONObject(i);
                        PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                        ID.add(PROBLEM_ID_INDEX);
                        Tab=ID.get(0);
                        data=new VideoInfo();
                        data.problem_id=objectData.getString("problem_id");
                        PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                        data.userID=objectData.getString("user_id");
                        data.ima_path= Urls.base+objectData.getString("img_path");
                        data.name=objectData.getString("nick_name");
                        data.time=objectData.getString("create_date");
                        data.content=objectData.getString("content");
                        data.url= Urls.base+objectData.getString("resource");
                        data.Thumb=Urls.base+objectData.get("thumb");
                        data.read_count=objectData.getInt("read_count");
                        data.replay_count=objectData.getInt("replay_count");
                        data.asmire_count=objectData.getInt("admire_count");
                        ListData.add(data);
                        adapter.setData(ListData);
                        videoList.setAdapter(adapter);
                        videoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                log.e("onclick","onclick");
                                Intent intent=new Intent();
                                data = ListData.get(position);
                                intent.putExtra("problem_id", data.problem_id);
                                intent.setClass(getActivity(),VideoDetail.class);
                                startActivity(intent);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });

    }




    //通过 set 方法在适配器中拿到这三个参数
    public void setPlayView(VideoPlayView playView) {
        this.playView = playView;
        playView.setMediaPlayerListenr(this);
        Log.i("XX", currentPosition + "");
        int[] curr = new int[2];
        currentItemView.getLocationOnScreen(curr);
        Log.i("TAG", curr[1] + "");
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

        if (totalItemCount == lastVisibieItem && scrollState == SCROLL_STATE_IDLE) {
            if (!isLoading) {
                isLoading = true;
                footer.findViewById(R.id.footer_layout).setVisibility(View.VISIBLE);
                // 加载更多
                handler = new Handler();
                handler.postDelayed(new Runnable(){
                    @Override
                    public void run() {

                        params.put("access_key",accessy_ley);
                        params.put("page_count",10);
                        params.put("user_id",userID);
                        params.put("problem_id_index",PROBLEM_ID_INDEX);
                        RequestHandle handle= client.post(Urls.VideoPer, params,new JsonHttpResponseHandler(){
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                super.onSuccess(statusCode, headers, response);
                                waitNetDataPop.dismiss();
                                String jsonStr=response.toString();
                                log.e("jsonstr",jsonStr);
                                try {
                                    JSONObject jsonObject=new JSONObject(jsonStr);
                                    JSONArray jsonArray=jsonObject.getJSONArray("data");
                                    for (int i=0;i<jsonArray.length();i++){
                                        JSONObject objectData=jsonArray.getJSONObject(i);
                                        PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                                        ID.add(PROBLEM_ID_INDEX);
                                        Tab=ID.get(0);
                                        data=new VideoInfo();
                                        data.userID=objectData.getString("user_id");
                                        data.problem_id=objectData.getString("problem_id");
                                        PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                                        data.ima_path= Urls.base+objectData.getString("img_path");
                                        data.name=objectData.getString("nick_name");
                                        data.time=objectData.getString("create_date");
                                        data.content=objectData.getString("content");
                                        data.url= Urls.base+objectData.getString("resource");
                                        data.Thumb=Urls.base+objectData.get("thumb");
                                        data.read_count=objectData.getInt("read_count");
                                        data.replay_count=objectData.getInt("replay_count");
                                        data.asmire_count=objectData.getInt("admire_count");
                                        ListData.add(data);

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                adapter.notifyDataSetChanged();
                            }
                        });
                        isLoading = false;
                        footer.findViewById(R.id.footer_layout).setVisibility(View.GONE);
                    }
                },1000);
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        this.lastVisibieItem = firstVisibleItem + visibleItemCount;
        this.totalItemCount = totalItemCount;
        Log.i("EE", "当前" + currentPosition);
        Log.i("EE", "可见的第一个" + videoList.getFirstVisiblePosition());
        if ((currentPosition < videoList.getFirstVisiblePosition() || currentPosition > videoList
                .getLastVisiblePosition()) && isPlaying && getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_PORTRAIT) {
            closeVideo();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (playView != null) {
            playView.play();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (playView != null) {
            playView.pause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (playView != null) {
            playView.stop();
        }
    }

    private void closeVideo() {
        currentPosition = -1;
        isPlaying = false;
        playView.stop();
        adapter.notifyDataSetChanged();
        playView = null;
        currentItemView = null;
    }

    /**
     * 在 manifest 中设置当前 activity, 当横竖屏切换时会执行该方法, 否则会 finish 重新执行一遍生命周期
     * @param newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (playView != null && newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

            // scrollDistance = currentItemView.getTop();

            //获取状态栏高度(如果设置沉浸式状态栏了就不需要获取)
            Rect rect = new Rect();
            getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            currentItemView.setLayoutParams(new AbsListView.
                    LayoutParams(ListView.LayoutParams.MATCH_PARENT,
                   getActivity().getWindowManager().getDefaultDisplay().getHeight() - rect.top));
            //设置横屏后要显示的当前的 itemView
            videoList.post(new Runnable() {
                @Override
                public void run() {
                    //一定要对添加这句话,否则无效,因为界面初始化完成后 listView 失去了焦点
                    videoList.requestFocusFromTouch();
                    videoList.setSelection(currentPosition);
                }
            });
            Log.i("XX", "横屏");
        } else if (playView != null && newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            //横屏时的设置会影响返回竖屏后的效果, 这里设置高度与 xml 文件中的高度相同
            Log.i("MM", currentPosition + "竖屏");
            currentItemView.setLayoutParams(new AbsListView.LayoutParams(
                    ListView.LayoutParams.MATCH_PARENT, getResources()
                    .getDimensionPixelOffset(R.dimen.itmes_height)));
            //本来想切换到竖屏后恢复到初始位置,但是上部出现空白
//            videoList.scrollBy(0, -(scrollDistance));
            //通过该方法恢复位置,不过还是有点小问题
            videoList.post(new Runnable() {
                @Override
                public void run() {
                    videoList.requestFocusFromTouch();
                    videoList.setSelection(firstVisiblePosition);
                }
            });
            Log.i("XX", "竖屏");
        }
    }

    /**
     * 当窗口处于横屏时,点击返回键退出横屏
     * @param keyCode
     * @param event
     * @return
     */

//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                if (playView != null) {
//                    playView.setExpendBtn(false);
//                }
//                return true;
//            }
//        }
//        return super.getActivity().onKeyDown(keyCode, event);
//    }

    /**
     * 由于视频在 listView 中,横屏后仍然后滑动
     * 此处判断当处于横屏时将滑动事件消耗掉
     * @param ev
     * @return
     */

    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_MOVE:
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    return true;
                }
                break;
        }
        return super.getActivity().dispatchTouchEvent(ev);
    }

    @Override
    public void onError() {
        closeVideo();
    }

    @Override
    public void onExpend() {
        firstVisiblePosition = videoList.getFirstVisiblePosition();
        //强制横屏
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    @Override
    public void onShrik() {
        //强制竖屏
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }


    private class MyAdapter extends BaseAdapter {

        private Context mContext;

        private List<VideoInfo> videoPaths;

        private VideoInfo bean;

        public MyAdapter(Context mContext) {
            this.mContext = mContext;
        }

        public void setData(List<VideoInfo> videoPaths) {
            this.videoPaths = videoPaths;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return videoPaths != null && videoPaths.size() > 0 ? videoPaths.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return videoPaths != null && videoPaths.size() > 0 ? videoPaths.get(position) : null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            bean=videoPaths.get(position);
            log.e("bean",bean.toString());
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.battle_new_listview_item, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.play_btn = (ImageView) convertView.findViewById(R.id.play_btn);
                viewHolder.show_layout = (FrameLayout) convertView.findViewById(R.id.show_layout);
                viewHolder.play_view = (VideoPlayView) convertView.findViewById(R.id.video_play_view);
                viewHolder.icon=(RoundImageView) convertView.findViewById(R.id.battle_new_head);
                viewHolder.name=(TextView)convertView.findViewById(R.id.battle_new_name);
                viewHolder.time=(TextView)convertView.findViewById(R.id.battle_new_time);
                viewHolder.content=(TextView)convertView.findViewById(R.id.battle_new_text);
                viewHolder.Img=(ImageView)convertView.findViewById(R.id.battlt_img);
                viewHolder.read_count=(TextView)convertView.findViewById(R.id.battle_new_viewNum);
                viewHolder.reply_count=(TextView) convertView.findViewById(R.id.battle_new_commentNum);
                viewHolder.good_count=(TextView)convertView.findViewById(R.id.battle_new_goodNum) ;

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            Picasso.with(getContext()).load(bean.ima_path).into(viewHolder.icon);
            viewHolder.icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("infoUserID",videoPaths.get(position).userID);
                    Log.e("infoUserIDImgClick",videoPaths.get(position).userID);
                    intent.setClass(mContext, more_myself.class);
                    mContext.startActivity(intent);
                }
            });
            viewHolder.name.setText(bean.name);
            viewHolder.time.setText(bean.time);
            viewHolder.content.setText(bean.content);
            viewHolder.read_count.setText(bean.read_count+"");
            viewHolder.reply_count.setText(bean.replay_count+"");
            viewHolder.good_count.setText(bean.asmire_count+"");
            boolean idddd;
            idddd=(bean.Thumb.equals(Urls.base));
            log.e("idddd",idddd+"");
            if(bean.Thumb.equals(Urls.base)){
            viewHolder.Img.setImageDrawable(getResources().getDrawable(R.mipmap.makefun));
            }else {
                Picasso.with(mContext).load(bean.Thumb).into(viewHolder.Img);

            }
      /*      当前页面播放视频
      viewHolder.play_btn.setOnClickListener(new MyClick(position,
                    viewHolder.play_view, viewHolder.show_layout, convertView));

            if (currentPosition == position) {
                viewHolder.play_view.setVisibility(View.VISIBLE);

            } else {
                viewHolder.play_view.setVisibility(View.GONE);
                viewHolder.show_layout.setVisibility(View.VISIBLE);
                viewHolder.play_view.stop();
            }
            */

      viewHolder.play_btn.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              Intent intent=new Intent();
              intent.setClass(mContext,VideoviewPlay.class);
              intent.putExtra("url",bean.url);
              startActivity(intent);
          }
      });
            return convertView;
        }

        private  class ViewHolder {
            private ImageView play_btn;//播放按钮
            private FrameLayout show_layout;
            private VideoPlayView play_view;
            public RoundImageView icon;
            public TextView name;
            public TextView time;
            public TextView content;
            public ImageView Img;
            public TextView read_count;
            public TextView reply_count;
            public TextView good_count;
        }

        class MyClick implements View.OnClickListener {
            private int position;
            private VideoPlayView playView;
            private FrameLayout show_layout;
            private View convertView;

            public MyClick(int position, VideoPlayView playView, FrameLayout show_layout, View convertView) {
                this.position = position;
                this.show_layout = show_layout;
                this.playView = playView;
                this.convertView = convertView;
            }

            @Override
            public void onClick(View v) {
                isPlaying = true;
                currentPosition = position;
                show_layout.setVisibility(View.GONE);
                playView.setUrl(bean.url);
                currentItemView = convertView;
                setPlayView(playView);
                playView.openVideo();
                notifyDataSetChanged();
            }
        }
    }
}